package com.thor.palmmall.impl.elecharges;

import java.io.Serializable;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thor.palmmall.api.elecharges.EleChargesBill;

/**
 * @author NuoSa
 *
 * @since 1.0
 */
public class WebServiceClient implements Serializable {
  private static final long serialVersionUID = -6098705100204982141L;

  private static final Logger logger = LoggerFactory.getLogger(WebServiceClient.class);
  private String endPoint = "http://61.144.52.5:6060/tcmr/webservice/payment?wsdl";

  public String getEndPoint() {
    return endPoint;
  }

  public void setEndPoint(String endPoint) {
    this.endPoint = endPoint;
  }

  public String callGetDate(String userNumber) throws ServiceException, RemoteException {
    String targetNamespace = "http://service.webservice/";
    String method = "query";
    // 创建一个服务(service)调用(call)
    Service service = new Service();
    Call call = (Call) service.createCall();// 通过service创建call对象
    // 设置service所在URL
    call.setTargetEndpointAddress(endPoint);
    call.setOperationName(new QName(targetNamespace, method));
    call.setUseSOAPAction(true);
    call.addParameter(new QName(targetNamespace, "arg0"),
        org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);// 接口的参数
    // call.setReturnClass(org.w3c.dom.Element.class);
    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
    // String path = targetNamespace + method;
    call.setEncodingStyle("UTF-8");
    // call.setSOAPActionURI(path);

    Object ret = call.invoke(new Object[] {
        userNumber });
    return ret.toString();

  }

  /**
   * 查询电表的历史数据及倍率信息
   * 
   * @param userId
   *          用户号
   * @param date
   *          数据日期
   * @return
   * @throws ServiceException
   * @throws RemoteException
   */
  public String queryFreezeDataAndCT(String userId, Date date)
      throws ServiceException, RemoteException {

    String targetNamespace = "http://service.webservice/";
    String method = "queryFreezeDataAndCT";
    // 创建一个服务(service)调用(call)
    Service service = new Service();
    Call call = (Call) service.createCall();// 通过service创建call对象
    // 设置service所在URL
    call.setTargetEndpointAddress(endPoint);
    call.setOperationName(new QName(targetNamespace, method));
    call.setUseSOAPAction(true);
    call.addParameter(new QName(targetNamespace, "arg0"),
        org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);// 接口的参数
    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
    call.setEncodingStyle("UTF-8");

    String queryParam = createQueryParam(userId, date);
    Object ret = call.invoke(new Object[] {
        queryParam });
    return ret.toString();

  }

  /**
   * 生成查询参数
   * 
   * @param userId
   *          用户id
   * @param date
   *          日期 yyyy-MM-dd
   * @return
   */
  private String createQueryParam(String userId, Date date) {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    String datarq = fmt.format(date == null ? new Date() : date);

    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='GB2312' standalone='no'?>");
    sb.append("<dataset>");
    sb.append("<parameter name='userId'>" + userId + "</parameter>");
    sb.append("<parameter name='datarq'>" + datarq + "</parameter>");
    sb.append("</dataset>");
    return sb.toString();
  }

  public String callPut(EleChargesBill eleChargesBill) throws ServiceException, RemoteException {
    logger.info("---------------------电费充值单同步开始--------------------------");
    String targetNamespace = "http://service.webservice/";
    String method = "payInfo";
    // 创建一个服务(service)调用(call)
    Service service = new Service();
    Call call = (Call) service.createCall();// 通过service创建call对象
    // 设置service所在URL
    logger.info("充值单同步服务路径:" + endPoint);
    call.setTargetEndpointAddress(endPoint);
    call.setOperationName(new QName(targetNamespace, method));
    call.setUseSOAPAction(true);
    call.addParameter(new QName(targetNamespace, "arg0"),
        org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);// 接口的参数
    // call.setReturnClass(org.w3c.dom.Element.class);
    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
    // String path = targetNamespace + method;
    call.setEncodingStyle("UTF-8");
    // call.setSOAPActionURI(path);
    String paydata = createPayDate(eleChargesBill);
    logger.info("充值单同步参数: " + paydata);
    Object ret = call.invoke(new Object[] {
        paydata });
    logger.info("充值单同步结果: " + ret);
    logger.info("---------------------电费充值单同步结束-------------------------");
    return ret.toString();
  }

  private String createPayDate(EleChargesBill eleChargesBill) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String tranNo = eleChargesBill.getTransactioNo();
    String userId = eleChargesBill.getUserNumber();
    BigDecimal amount = eleChargesBill.getAmount();
    String time = dateFormat.format(
        eleChargesBill.getActionTime() == null ? new Date() : eleChargesBill.getActionTime());

    int tranType = 0;
    switch (eleChargesBill.getMethod()) {
    case alipay:
      tranType = 8;
      break;
    case unionpay:
      tranType = 13;
      break;
    case wechat:
      tranType = 7;
      break;
    default:
      tranType = 0;
      break;
    }
    StringBuilder payData = new StringBuilder();
    payData.append("<?xml version='1.0' encoding='GB2312' standalone='no'?>");
    payData.append("<dataset>");
    payData.append("<parameter name='TRANSID'>" + tranNo + "</parameter>");
    payData.append("<parameter name='USERID'>" + userId + "</parameter>");
    payData.append("<parameter name='AMOUNT'>" + amount + "</parameter>");
    payData.append("<parameter name='TIME'>" + time + "</parameter>");
    payData.append("<parameter name='TRANS_TYPE'>" + tranType + "</parameter>");
    payData.append("</dataset>");
    return payData.toString();
  }

}
